import logging

from django import http
from django.shortcuts import render
from django.views.generic import View
from areas.models import Area
from urtils.response_code import RETCODE
from django.core.cache import cache


# 日志输出器
logger = logging.getLogger('django')

class AreasView(View):
    """省市区三级联动"""
    def get(self, request):
        # 判断当前是要查询省级还是区县及
        area_id = request.GET.get('area_id')
        if not area_id:

            # 判断省市数据缓存
            province_list = cache.get('province_list')
            if not province_list:
                try:
                    # 查询省级数据
                    province_model_list = Area.objects.filter(parent_id__isnull=True)
                    # 将模型列表转为字典列表
                    province_list = []
                    for province_mode in province_model_list:
                        province_dict = {
                            'id':province_mode.id,
                            'name':province_mode.name
                        }
                        province_list.append(province_dict)
                    # 缓存省市数据
                    cache.set('province_list', province_list, 3600)

                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '查询省份数据失败'})
            # 响应结果
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list})

        else:
            # 判断市或区缓存数据
            sub_data = cache.get('sub_area_' + area_id)
            if not sub_data:
                try:
                    # 查询城市或识市区数据
                    parent_model = Area.objects.get(id=area_id)
                    sub_parent_model = parent_model.subs.all()
                    # 将子集模型表转换为列表
                    subs = []
                    for sub_model in sub_parent_model:
                        subs_dict = {
                            'id': sub_model.id,
                            'name': sub_model.name
                        }
                        subs.append(subs_dict)
                    # 构建子集ｊｓｏｎ数据
                    sub_data = {
                        'id': parent_model.id,
                        'name': parent_model.name,
                        'subs': subs
                    }
                    # 缓存市区数据
                    cache.set('sub_area'+area_id, sub_data)

                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '查询省区县数据失败'})
            # 响应城镇或县区数据
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'sub_data': sub_data})